<template>
  <div>
    <div class="title" style="text-align:left">
      <font-awesome-icon icon="language" />&nbsp;商品编辑
    </div>
    <div class="block-line">&nbsp;</div>
    <el-form ref="form" :model="form" label-width="120px" :rules="rules"
      label-position="right" size="small" :inline-message="true">
      <el-form-item label="商品名称：" :sm="5" prop="title">
        <el-col :sm="16">
          <el-input v-model="form.title" placeholder="请输入商品名称" suffix-icon="el-icon-s-custom"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="商品价格：" :sm="3" prop="title">
        <el-col :sm="16">
          <el-input v-model="form.price" placeholder="请输入商品价格" suffix-icon="el-icon-s-custom"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="商品类别：" :sm="3" prop="iid">
        <el-col :sm="16" class="text-left">
          <el-select v-model="form.iid" placeholder="请选择所属分类" @change="loadSubitemData" style="width:100%">
            <el-option v-for="item in itemData" :key="item.iid"
              :label="item.title" :value="item.iid"></el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="商品子类别：" :sm="3" prop="siid">
        <el-col :sm="16" class="text-left">
          <el-select v-model="form.siid" placeholder="请选择所属子分类" style="width:100%">
            <el-option v-for="item in subitemData" :key="item.iid"
              :label="item.title" :value="item.iid"></el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="商品图片：" :sm="3" prop="photo">
        <el-col :sm="16">
          <el-upload class="upload-demo" drag multiple list-type="picture"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
            action="/mallApi/back/goods/uploadPhoto" name="photo"
            :on-success="handleUploadPhotoSuccess" :on-remove="handlePhotoRemove"
            :file-list="goodsImgList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-col>
      </el-form-item>
      <el-form-item label="商品视频：" :sm="3" prop="video">
        <el-col :sm="16">
          <el-upload class="upload-demo" drag multiple list-type="picture"
            accept=".mp4"
            action="/mallApi/back/goods/uploadVideo" name="video"
            :on-success="handleUploadVideoSuccess" :on-remove="handleVideoRemove"
            :file-list="goodsVideoList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传MP4视频</div>
          </el-upload>
        </el-col>
      </el-form-item>
      <el-form-item label="商品状态：" :sm="3" prop="lock">
        <el-col :sm="16" style="text-align:left;">
          <el-radio-group v-model="form.lock">
            <el-radio :label="0">直接发布</el-radio>
            <el-radio :label="1">暂不发布</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item prop="content">
        <el-col :sm="16" style="text-align:left;">
          <editor v-model="form.content" :api-key="apikey" :init="init"/>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-col :sm="16">
          <el-button type="primary" @click="submitForm">修改</el-button>
          <el-button type="warning" @click="resetForm">重置</el-button>
        </el-col>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import Editor from '@tinymce/tinymce-vue'
import { Loading } from 'element-ui'
import {mapGetters} from 'vuex'
export default {
  components: {
    'editor': Editor
  },
  data () {
    return {
      init: {
        language: 'zh_CN',
        height: 500,
        menubar: false,
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount'
        ],
        toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help'
      },
      goodsImgList: [],
      goodsVideoList: [],
      itemData: [], // 商品分类信息
      subitemData: [], // 商品子分类信息
      form: {
        title: '', // 商品名称
        price: 0.0, // 商品价格
        video: '', // 商品介绍视频
        photo: '', // 商品图片
        iid: '', // 商品分类
        siid: '', // 商品子分类
        lock: 0, // 商品是否发布
        content: '' // 商品内容介绍
      },
      rules: {
        title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 50, message: '商品名称长度在2到50个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        iid: [
          { required: true, message: '请选择商品所属类别', trigger: 'blur' }
        ],
        siid: [
          { required: true, message: '请选择商品所属子类别', trigger: 'blur' }
        ],
        photo: [
          { required: true, message: '请选择商品图片', trigger: 'blur' }
        ],
        video: [
          { required: true, message: '请上传商品介绍视频', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入商品详细内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleUploadPhotoSuccess (res, file) { // 图片上传成功
      this.form.photo = res.data // 保存上传后的图片名称
      console.log(res)
      console.log(file)
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    handlePhotoRemove (file, fileList) { // 文件删除时的钩子函数
      console.log(file)
    },
    handleUploadVideoSuccess (res, file) { // 图片上传成功
      this.form.video = res.data // 保存上传后的图片名称
      console.log(res)
      console.log(file)
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    handleVideoRemove (file, fileList) { // 文件删除时的钩子函数
      console.log(file)
    },
    submitForm () { // 【开发】进行远程数据增加
      console.log(this.form) // 所有的数据都保存在form
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$back.goods.goodsAdd(this.form).then(res => { // 加载新闻数据信息
            console.log('商品发布状态：' + res.status)
          })
          const h = this.$createElement
          this.$notify({
            title: '发布成功',
            message: h('i', {style: 'color: teal'}, '新闻编写完成。')
          })
          this.resetForm() // 重置表单
          console.log('表单提交成功，等待数据处理！')
        } else {
          console.log('错误，表单验证失败，无法提交！')
          return false
        }
      })
    },
    resetForm () {
      console.log(this.errors)
      this.form = {
        title: '', // 商品名称
        price: 0.0, // 商品价格
        video: '', // 商品介绍视频
        photo: '', // 商品图片
        iid: '', // 商品分类
        siid: '', // 商品子分类
        lock: 0, // 商品是否发布
        content: '' // 商品内容介绍
      }
      this.$refs['form'].resetFields()
    },
    loadItemData () { // 【开发】分页数据加载操作
      let loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        setTimeout(() => {
          this.$back.goods.loadItem().then(res => { // 加载新闻数据信息
            this.itemData = res.data // 保存新闻列表数据
          })
          loadingInstance.close()
        }, 100)
      })
    },
    loadGoodsData () { // 根据id加载数据信息
      var gid = this.$route.params.gid // 根据参数获取要修改的商品id信息
      this.$back.goods.goodsLoad(gid).then(res => { // 加载新闻数据信息
        this.form = res.data // 保存新闻列表数据
        this.goodsImgList.push({'url': this.form.photo})
        this.goodsVideoList.push({'url': this.form.video})
      })
    },
    loadSubitemData (pid) { // 【开发】分页数据加载操作
      console.log('加载父项ID = ' + pid)
      let loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        setTimeout(() => {
          this.$back.goods.loadSubitem(pid).then(res => { // 加载新闻数据信息
            this.subitemData = res.data // 保存新闻列表数据
          })
          loadingInstance.close()
        }, 100)
      })
    }
  },
  computed: {
    ...mapGetters(['apikey'])
  },
  mounted () {
    this.loadGoodsData() // 加载商品数据
    this.loadItemData() // 加载商品分类信息
    this.loadSubitemData(this.form.iid)
  }
}
</script>
